package com.ddch.testmessager;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

/**
 * created by 韦敏敏
 * on 2019/12/19
 */
public class MessagerService extends Service {
    private static final String TAG = "liaoming";
private MessagerHandler mHandler = new MessagerHandler();
private Messenger mMessenger = new Messenger(mHandler);
    public MessagerService() {
        Log.d(TAG, "MessagerService MessagerService()");
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Log.d(TAG, "MessagerService IBinder");
        return mMessenger.getBinder();
    }
    private static class MessagerHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
         // 取出客户端的消息内容
            Bundle bundle = msg.getData();
            String clientMsg = bundle.getString("client");
            Log.d(TAG, "来自客户端的消息: " + clientMsg);
            // 新建一个Message对象，作为回复客户端的对象
            Message message = Message.obtain();
            Bundle bundle1 = new Bundle();
            bundle1.putString("service", "今天就不去了，还有很多东西要学!!!");
            message.setData(bundle1);
            try {
                msg.replyTo.send(message);
            } catch (RemoteException e) {
                e.printStackTrace();
            }
        }
    }

    @SuppressLint("WrongConstant")
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d(TAG, "onStartCommand");
        flags = START_STICKY;
        return START_STICKY_COMPATIBILITY;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "MessagerService  onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "MessagerService  onDestroy");
    }

    @Override
    public void onRebind(Intent intent) {
        super.onRebind(intent);
        Log.d(TAG, "MessagerService  onRebind");
    }

    @Override
    public boolean onUnbind(Intent intent) {
        Log.d(TAG, "MessagerService  onUnbind");
        return super.onUnbind(intent);
    }
}
